import { useState, useEffect, useRef, useMemo } from 'react';
import { useNavigate } from 'react-router-dom';
import './SourceMaterial.css';

// 搜索框样式
const searchSectionStyle = {
  padding: '20px',
  background: '#fff',
  borderBottom: '1px solid #e0e0e0',
  position: 'relative' as const,
};

const searchContainerStyle = {
  maxWidth: '800px',
  margin: '0 auto',
  display: 'flex',
  gap: '12px',
  alignItems: 'center',
};

const searchInputWrapperStyle = {
  flex: 1,
  position: 'relative' as const,
  display: 'flex',
  alignItems: 'center',
  backgroundColor: 'white',
  border: '2px solid #e8e8e8',
  borderRadius: '12px',
  padding: '0 16px',
  transition: 'border-color 0.2s',
  boxShadow: '0 4px 20px rgba(0, 0, 0, 0.1)',
  minHeight: '56px',
};

const searchInputStyle = {
  flex: 1,
  border: 'none',
  outline: 'none',
  fontSize: '16px',
  padding: '16px 0',
  background: 'transparent',
  color: '#333',
};

const searchButtonStyle = {
  padding: '16px 24px',
  backgroundColor: '#1890ff',
  color: 'white',
  border: 'none',
  borderRadius: '12px',
  fontSize: '16px',
  fontWeight: '500',
  cursor: 'pointer',
  transition: 'all 0.2s',
  whiteSpace: 'nowrap' as const,
  boxShadow: '0 4px 20px rgba(24, 144, 255, 0.3)',
  flexShrink: 0,
};



// 随机图片生成函数
function getRandomImg(seed: string) {
  return `https://picsum.photos/seed/${seed}/300/400`;
}
// 生成随机高度函数
function getRandomHeight() {
  return Math.floor(Math.random() * 150) + 250; // 250-400px 随机高度
}
// 生成大量模拟分组和图片
const GROUP_COUNT = 15;
const ITEMS_PER_GROUP = 8;
const allGroups = Array.from({ length: GROUP_COUNT }).map((_, i) => ({
  title: `分组${i + 1}`,
  items: Array.from({ length: ITEMS_PER_GROUP }).map((_, j) => ({
    title: `素材${i + 1}-${j + 1}`,
    img: getRandomImg(`${i + 1}-${j + 1}`),
    height: getRandomHeight(),
  })),
}));

const hot = [
  { title: '海报', desc: '10w+质感海报等你来撩', img: getRandomImg('hot1') },
  { title: '邀请函', desc: '商务婚礼年会庆典等各主题邀请函', img: getRandomImg('hot2') },
  { title: '喜报', desc: '大气喜庆感模板合集', img: getRandomImg('hot3') },
  { title: '箭头', desc: '小箭头，简约而不简单', img: getRandomImg('hot4') },
  { title: '倒计时', desc: '打造专属时刻的仪式感', img: getRandomImg('hot5') },
];

const PAGE_SIZE = 3;

function Index() {
  const [groups, setGroups] = useState(allGroups.slice(0, PAGE_SIZE));
  const [page, setPage] = useState(1);
  const loadingRef = useRef<HTMLDivElement | null>(null);
  const [loading, setLoading] = useState(false);
  const [searchKeyword, setSearchKeyword] = useState('');
  const [layoutType, setLayoutType] = useState<'fixed' | 'waterfall'>('fixed');
  const [windowWidth, setWindowWidth] = useState(typeof window !== 'undefined' ? window.innerWidth : 1200);
  const navigate = useNavigate();

  // 监听窗口大小变化
  useEffect(() => {
    const handleResize = () => {
      setWindowWidth(window.innerWidth);
    };
    window.addEventListener('resize', handleResize);
    return () => window.removeEventListener('resize', handleResize);
  }, []);

  // 根据搜索关键词过滤素材
  const filteredGroups = useMemo(() => {
    if (!searchKeyword.trim()) {
      return groups;
    }
    return groups.map(group => ({
      ...group,
      items: group.items.filter(item =>
        item.title.toLowerCase().includes(searchKeyword.toLowerCase())
      )
    })).filter(group => group.items.length > 0);
  }, [groups, searchKeyword]);

  // 卡片样式
  const cardStyle = {
    display: 'flex',
    flexDirection: 'column' as const,
    alignItems: 'center',
    backgroundColor: 'white',
    borderRadius: '8px',
    overflow: 'hidden',
    boxShadow: '0 2px 8px rgba(0,0,0,0.1)',
    transition: 'transform 0.2s, box-shadow 0.2s',
  };
  const waterfallCardStyle = {
    ...cardStyle,
    breakInside: 'avoid' as const,
    marginBottom: '16px',
  };

  // 获取响应式列数
  const getColumnCount = () => {
    if (windowWidth <= 480) return 1;
    if (windowWidth <= 768) return 2;
    if (windowWidth <= 1200) return 3;
    return 4;
  };
  // 动态瀑布流样式
  const getWaterfallStyle = () => ({
    columnCount: getColumnCount(),
    columnGap: '16px',
    columnFill: 'balance' as const,
  });
  // 动态网格样式
  const getFixedGridStyle = () => ({
    display: 'grid',
    gridTemplateColumns: `repeat(${getColumnCount()}, 1fr)`,
    gap: '16px',
  });

  useEffect(() => {
    if (page === 1) return;
    setLoading(true);
    setTimeout(() => {
      setGroups(allGroups.slice(0, PAGE_SIZE * page));
      setLoading(false);
    }, 600);
  }, [page]);

  useEffect(() => {
    const handleScroll = () => {
      if (!loadingRef.current) return;
      const { bottom } = loadingRef.current.getBoundingClientRect();
      if (bottom < window.innerHeight + 100 && groups.length < allGroups.length && !loading) {
        setPage(p => p + 1);
      }
    };
    window.addEventListener('scroll', handleScroll);
    return () => window.removeEventListener('scroll', handleScroll);
  }, [groups.length, loading]);

  return (
    <div className="sm-page">
      {/* 搜索框和布局切换 */}
      <div style={searchSectionStyle}>
        <div style={searchContainerStyle}>
          <div style={searchInputWrapperStyle}>
            {/* 搜索图标 */}
            <svg style={{ width: '20px', height: '20px', color: '#999', marginRight: '12px' }} viewBox="0 0 20 20" fill="none">
              <path d="M19 19L13 13M15 8C15 11.866 11.866 15 8 15C4.13401 15 1 11.866 1 8C1 4.13401 4.13401 1 8 1C11.866 1 15 4.13401 15 8Z" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
            </svg>
            <input
              type="text"
              style={searchInputStyle}
              placeholder="请输入关键词"
              value={searchKeyword}
              onChange={(e) => setSearchKeyword(e.target.value)}
              onKeyPress={(e) => {
                if (e.key === 'Enter') {
                  // 搜索功能已通过onChange实现实时搜索
                }
              }}
            />
            {/* 相机图标 */}
            <svg style={{ width: '20px', height: '20px', color: '#999', marginLeft: '12px', cursor: 'pointer' }} viewBox="0 0 20 20" fill="none">
              <path d="M17 12C17 12.5304 16.7893 13.0391 16.4142 13.4142C16.0391 13.7893 15.5304 14 15 14H5C4.46957 14 3.96086 13.7893 3.58579 13.4142C3.21071 13.0391 3 12.5304 3 12V8C3 7.46957 3.21071 6.96086 3.58579 6.58579C3.96086 6.21071 4.46957 6 5 6H6L7 4H13L14 6H15C15.5304 6 16.0391 6.21071 16.4142 6.58579C16.7893 6.96086 17 7.46957 17 8V12Z" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
              <path d="M10 11C11.1046 11 12 10.1046 12 9C12 7.89543 11.1046 7 10 7C8.89543 7 8 7.89543 8 9C8 10.1046 8.89543 11 10 11Z" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
            </svg>
          </div>
          <button
            style={searchButtonStyle}
            onMouseEnter={(e) => {
              e.currentTarget.style.backgroundColor = '#40a9ff';
              e.currentTarget.style.transform = 'translateY(-1px)';
            }}
            onMouseLeave={(e) => {
              e.currentTarget.style.backgroundColor = '#1890ff';
              e.currentTarget.style.transform = 'translateY(0)';
            }}
          >
            搜索
          </button>
          {/* 布局切换按钮 */}
          <button
            style={{
              ...searchButtonStyle,
              backgroundColor: layoutType === 'waterfall' ? '#52c41a' : '#1890ff',
            }}
            onMouseEnter={(e) => {
              e.currentTarget.style.backgroundColor = layoutType === 'waterfall' ? '#73d13d' : '#40a9ff';
              e.currentTarget.style.transform = 'translateY(-1px)';
            }}
            onMouseLeave={(e) => {
              e.currentTarget.style.backgroundColor = layoutType === 'waterfall' ? '#52c41a' : '#1890ff';
              e.currentTarget.style.transform = 'translateY(0)';
            }}
            onClick={() => setLayoutType(layoutType === 'fixed' ? 'waterfall' : 'fixed')}
          >
            {layoutType === 'fixed' ? '不定高' : '定高'}
          </button>
        </div>
      </div>
      <div className="sm-groups">
        {filteredGroups.map((group) => (
          <div className="sm-group" key={group.title}>
            <div className="sm-group-header">
              <span>{group.title}</span>
              <span className="sm-more">更多 &gt;</span>
            </div>
            <div
              className="sm-cards"
              style={layoutType === 'fixed' ? getFixedGridStyle() : getWaterfallStyle()}
            >
              {group.items.map((item) => (
                <div
                  className="sm-card"
                  key={item.title}
                  style={{
                    ...(layoutType === 'fixed' ? cardStyle : waterfallCardStyle),
                    cursor: 'pointer',
                  }}
                  onMouseEnter={(e) => {
                    e.currentTarget.style.transform = 'translateY(-4px)';
                    e.currentTarget.style.boxShadow = '0 8px 25px rgba(0,0,0,0.15)';
                  }}
                  onMouseLeave={(e) => {
                    e.currentTarget.style.transform = 'translateY(0)';
                    e.currentTarget.style.boxShadow = '0 2px 8px rgba(0,0,0,0.1)';
                  }}
                >
                  <img
                    src={item.img}
                    alt={item.title}
                    style={{
                      width: '100%',
                      height: layoutType === 'fixed' ? 'auto' : `${item.height}px`,
                      objectFit: 'cover',
                      display: 'block',
                    }}
                  />
                  <div style={{
                    padding: '12px',
                    textAlign: 'center',
                    fontSize: '14px',
                    color: '#333',
                    fontWeight: '500',
                    width: '100%',
                    boxSizing: 'border-box' as const,
                  }}>
                    {item.title}
                  </div>
                </div>
              ))}
            </div>
          </div>
        ))}
      </div>
      <div ref={loadingRef} className="sm-loading">
        {groups.length < allGroups.length ? (loading ? '加载中...' : '') : '已加载全部'}
      </div>
      <div className="sm-hot-title">热搜推荐</div>
      <div className="sm-hot-list">
        {hot.map(item => (
          <div className="sm-hot-item" key={item.title}>
            <img src={item.img} alt={item.title} />
            <div className="sm-hot-item-title">{item.title}</div>
            <div className="sm-hot-item-desc">{item.desc}</div>
          </div>
        ))}
      </div>
      {/* 客服悬浮按钮 */}
      <div className="sm-customer-service" onClick={() => navigate('/customer-service')} style={{ position: 'fixed', right: '32px', bottom: '32px', zIndex: 1000, boxShadow: '0 2px 8px rgba(226,60,60,0.08)' }}>
        <svg width="48" height="48" viewBox="0 0 36 36" fill="none" xmlns="http://www.w3.org/2000/svg">
          <circle cx="18" cy="18" r="18" fill="#fff" stroke="#e23c3c" strokeWidth="2"/>
          <path d="M9 20v-2a9 9 0 1 1 18 0v2" stroke="#e23c3c" strokeWidth="2" fill="none"/>
          <rect x="8" y="20" width="4" height="8" rx="2" fill="#e23c3c"/>
          <rect x="24" y="20" width="4" height="8" rx="2" fill="#e23c3c"/>
          <circle cx="18" cy="24" r="2" fill="#e23c3c"/>
        </svg>
      </div>
      {/* 一键返回顶部按钮 */}
      <div onClick={() => window.scrollTo({ top: 0, behavior: 'smooth' })} style={{ position: 'fixed', right: '32px', bottom: '146px', zIndex: 1000, background: '#e23c3c', borderRadius: '50%', width: '44px', height: '44px', display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer', boxShadow: '0 2px 8px rgba(226,60,60,0.08)' }}>
        <svg width="28" height="28" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
          <path d="M12 19V5M12 5l7 7M12 5L5 12" stroke="#fff" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
        </svg>
      </div>
      {/* 一键滚动到底部按钮 */}
      <div onClick={() => window.scrollTo({ top: document.body.scrollHeight, behavior: 'smooth' })} style={{ position: 'fixed', right: '32px', bottom: '90px', zIndex: 1000, background: '#e23c3c', borderRadius: '50%', width: '44px', height: '44px', display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer', boxShadow: '0 2px 8px rgba(226,60,60,0.08)' }}>
        <svg width="28" height="28" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
          <path d="M12 5v14M12 19l7-7M12 19l-7-7" stroke="#fff" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
        </svg>
      </div>
    </div>
  );
}

export default Index;
